import Adjust from '@adjustcom/adjust-web-sdk';
import { watchOnce } from '@peng_kai/kit/libs/vueuse';
import { flzxsqc, hasCookieName, setCookie } from '~/utils';

export function useAdjustInit() {
  const appStore = useAppStore();

  watchOnce(() => appStore.handshake, (hd) => {
    if (!hd?.adjust_app_token)
      return;
    Adjust.initSdk({
      appToken: hd?.adjust_app_token, // required
      environment: 'production', // required, 'production' or 'sandbox' in case you are testing SDK locally with your web app
      logLevel: 'info',
    });
    Promise.all([Adjust.waitForAttribution(), Adjust.waitForWebUUID()]).then(([attr, uuid]) => {
      setCookie('adjust', encodeURIComponent(flzxsqc(JSON.stringify({ web_uuid: uuid, ad_id: attr.adid }))));
    });

    if (hd?.promotion_channel?.event_install_token && !hasCookieName('adjust')) {
      Adjust.trackEvent({
        eventToken: hd.promotion_channel.event_install_token,
      });
    }
  });
}
